exports.main = async context => {
  const cloud = context.cloud;
  const collectionName = 'pfIDC';
  const parsedPatterns = parsePatterns(context.data.patterns);

  try {
    const collection = cloud.db.collection(collectionName);
    const deletedCount = await clear(collection);
    const insertedIds = await collection.insertMany(parsedPatterns);

    return {
      success: true,
      result: insertedIds
    }
  } catch (error) {
    return {
      success: false,
      error
    };
  }
};

function clear(collection) {
  return collection.deleteMany({
    _id: { $type : 'string' }
  });
}

function parsePatterns(patterns) {
  return replaceWordings(patterns).map(p => ({
    id: p.id,
    ...p.payload
  }))
}

function replaceWordings(patterns) {
  const DOMAIN = "app-master.youcamapi.cn";

  const strReplaced = JSON.stringify(patterns)
    .replace(/attr_|\\r|\\n|\\t/g, "")
    .replace(/\${DOMAIN}/g, DOMAIN);
  return JSON.parse(strReplaced)
}